package com.weiaibenpao.demo.chislim.base;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by wlx on 2017/12/4.
 */

public abstract class BaseActivity<V extends BaseView,T extends BasePresenter<V>> extends AppCompatActivity {
    public T mPresenter;
    public ImmersionBar immersionBar;
    private Unbinder bind;
    private InputMethodManager imm;
    private AlertDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (setLayoutResourceID()!=0){
            setContentView(setLayoutResourceID());
        }
        bind = ButterKnife.bind(this);
        imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        /**
         * 沉浸式状态栏
         * 白底黑字
         */
        immersionBar = ImmersionBar.with(this);
        initImmersionBar();
        /**
         * presenter
         */
        mPresenter=initPresenter();
        if (mPresenter!=null){
            mPresenter.attack((V) this);
        }

        init(savedInstanceState);
//        checkPerMissions();
//        ActivityCollector.addActivity(this);
//        Logger.e("BaseActivity--onCreate: " + getClass().getSimpleName());
    }
    /**
     * 权限检查
     *
     * @param
     */
    public void checkPerMissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            startDo();
        }
    }

    protected void  startDo(){};
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            startDo();

        } else {
            showDialogTipUserGoToAppSetting();
        }
    }
    protected void initImmersionBar() {
        immersionBar
                .statusBarDarkFont(true,0.2f)
//                .statusBarColor(R.color.white)//状态栏颜色，不写默认透明色
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                .init();
    }

    /**
     * 布局
     * @return
     */
    @LayoutRes
    public abstract int setLayoutResourceID();

    /**
     *
     * @return Presenter
     */
    public  T initPresenter(){
        return null;
    }

    /**
     * 初始化view
     */
   public abstract void init(Bundle savedInstanceState);

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter!=null){
            mPresenter.detach();
            mPresenter.onDestroy();
        }
        if (immersionBar!=null){
            immersionBar.destroy();// //必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        }
        //操作不当会导致bug，例如在具体界面的onDestroy的super.onDestroy后操作某些View对象，会报NullPointerException，因为这里unbind了
        //正确姿势是：在super.onDestroy前面执行你需要的view操作--ZJL
        bind.unbind();
//        ActivityMangerUtils.getInstance().removeActivity(this);//在魅族手机上会有bug。。。
//        ActivityCollector.removeActivity(this);
    }
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (imm.isActive()&&ev.getAction() == MotionEvent.ACTION_DOWN){
                View v = getCurrentFocus();
                if (isShouldHideKeyboard(v, ev)) {
                    hideKeyboard(v.getWindowToken(), v);
                }

        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token, View v) {
        if (token != null) {
            if (imm.isActive()) {

                imm.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 123:
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        // 检查该权限是否已经获取
                        int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
                        // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                        if (i != PackageManager.PERMISSION_GRANTED) {
                            // 提示用户应该去应用设置界面手动开启权限
                            showDialogTipUserGoToAppSetting();
                        } else {
                            if (dialog != null && dialog.isShowing()) {
                                dialog.dismiss();
                            }

                        }
                        break;
                    }
            }
        }

    }
    // 提示用户去应用设置界面手动开启权限
    private void showDialogTipUserGoToAppSetting() {
        String set = "请在-应用设置-权限管理\n允许东极圈使用读写手机储存权限，确保该功能的正常使用";
        dialog = new AlertDialog.Builder(this)
                .setTitle("读写手机储存权限不可用")
                .setMessage(set)
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 跳转到应用设置界面
                        goToAppSetting();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Toast.makeText(BaseActivity.this, "请在应用管理中打开相关访问权限，确保该功能的正常使用", Toast.LENGTH_SHORT).show();
                    }
                }).setCancelable(false).show();
    }

    // 跳转到当前应用的设置界面
    private void goToAppSetting() {
        Intent intent = new Intent();

        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);

        startActivityForResult(intent, 123);
    }

}
